package cn.cloud.service;

import cn.cloud.handler.ConsumerHandler;
import cn.cloud.pojo.MQEntity;
import cn.cloud.utils.SerializeUtils;
import com.alibaba.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Cloud on 2018/3/18 0018.
 */
public abstract class AbstractConsumer<T extends MQEntity> implements ConsumerHandler {
    protected Logger logger = LoggerFactory.getLogger(AbstractConsumer.class);

    public void handlerMessage(MessageExt msg) {
        try {
            T entity = doStart(msg);
            execute(entity);
            doEnd(entity);
        } catch (Exception e) {
            logger.error("处理mq消息异常。", e);
        }
    }

    /**
     * 解析mq消息前置处理
     *
     * @param msg
     */
    protected T doStart(MessageExt msg) {
        return (T) SerializeUtils.deserialize(msg.getBody());
    }

    /**
     * 解析mq消息后置处理
     *
     * @param entity
     */
    protected void doEnd(T entity) {

    }

    /**
     * 解析mq消息 MessageExt
     *
     * @param entity
     */
    public abstract void execute(T entity);
}
